﻿using System;
using System.Threading;

namespace MSIACCSL2.Libs
{
  public class NavigationAsyncResult : IAsyncResult
    {
        private AsyncCallback _cb;
        private object _state;
        private ManualResetEvent _event;
        private bool _completed = false;
        private object _lock = new object();
        private bool _sync = false;

        // Assumed that these properties are accessed from a single thread
        public object Result { get; set; }
        public string PageUri { get; set; }
        public string TargetUri { get; set; }
        public string AssemblyUri { get; set; }

        public NavigationAsyncResult(AsyncCallback cb, object state)
        {
            _cb = cb;
            _state = state;
        }

        public Object AsyncState
        {
            get { return _state; }
        }

        public bool CompletedSynchronously
        {
            get { lock (_lock) { return _sync; } }
        }

        public bool IsCompleted
        {
            get { lock (_lock) { return _completed; } }
        }

        public WaitHandle AsyncWaitHandle
        {
            get
            {
                lock (_lock)
                {
                    if (_event == null)
                        _event = new ManualResetEvent(IsCompleted);
                    return _event;
                }
            }
        }

        public void CompleteCall()
        {
            CompleteCall(false);
        }

        public void CompleteCall(bool synchronously)
        {
            lock (_lock)
            {
                _completed = true;
                _sync = synchronously;
                if (_event != null)
                    _event.Set();
            }

            if (_cb != null)
                _cb(this);
        }
    }
}
